<template>
  <div class="app-container">

    <el-form
      ref="dataForm3"
      :rules="rules3"
      :model="bonusTemp"
      label-position="right"
      label-width="100px"
      style="">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="红包名称" label-width="150px" prop="bonusName">
            <el-input v-model="bonusTemp.bonusName"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="红包所值金额" label-width="150px" prop="bonusMoney">
            <el-input v-model.number="bonusTemp.bonusMoney"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单最少金额" label-width="150px" prop="minGoodsAmount">
            <el-input v-model.number="bonusTemp.minGoodsAmount"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="红包有效期" label-width="150px" prop="expireTime">
            <el-radio-group v-model="selectExpireType">
              <el-radio v-for="item in expireOptions" :key="item.id" :label="item.id" @change="changeExpireType">{{
                item.text }}
              </el-radio>
            </el-radio-group>
            <el-input-number v-show="isShow" v-model="selectExpireDay" :min="1" controls-position="right"/>
            <!--<el-date-picker-->
              <!--v-model="bonusTemp.expireTime"-->
              <!--type="datetime"-->
              <!--placeholder="选择日期"-->
              <!--value-format="timestamp"/>-->
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="红包可用产品" label-width="150px" prop="useGoods">
            <el-transfer v-model="selectUseGoods" :props="{key: 'pid',label: 'pname'}" :data="productData"/>
            <span style="color: red">没选为所有产品可用</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="排序" label-width="150px" prop="sort">
            <el-input v-model.number="bonusTemp.sort"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户文件" label-width="150px" prop="sort">
            <el-upload
              ref="upload"
              :http-request="handleFile"
              :on-change="path_file"
              :file-list="path"
              action=""
              class="upload-demo">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-col :span="12" :offset="8">
          <el-button type="primary" @click="addBonus">立即创建</el-button>
        </el-col>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
  import sxProductBasicInfoApi from '@/api/manage/SxProductBasicInfoApi'
  import SxUserInfoApi from '@/api/manage/SxUserInfoApi'
  import SxBonusRecordApi from '@/api/manage/SxBonusRecordApi'
  import SxUserScoreRecordApi from '@/api/manage/SxUserScoreRecordApi'
  import waves from '@/directive/waves' // Waves directive
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  export default {
    directives: {waves},
    components: {Pagination},
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      },
      validFilter(status) {
        const statusMap = {
          1: '有效',
          0: '作废'
        }
        return statusMap[status]
      },
      timeFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      }
    },
    data() {
      return {
        dialogBonusFormVisible: false,
        bonusTemp: {},
        productData: [],
        selectUseGoods: [],
        isShow: false,
        selectExpireType: 3,
        selectExpireDay: 30,
        expireOptions: [
          {id: 1, text: '7天', expireDay: 7},
          {id: 2, text: '15天', expireDay: 15},
          {id: 3, text: '一个月', expireDay: 30},
          {id: 4, text: '三个月', expireDay: 90},
          {id: 5, text: '半年', expireDay: 180},
          {id: 6, text: '一年', expireDay: 365},
          {id: 7, text: '其他', expireDay: 0}
        ],
        rules3: { // 编辑框校验规则
          bonusName: [{required: true, message: '红包管理名称', trigger: 'change'}],
          bonusMoney: [{required: true, message: '红包金额', trigger: 'change'}],
          minGoodsAmount: [{required: true, message: '红包订单金额', trigger: 'change'}],
          expireTime: [{required: true, message: '红包过期时间', trigger: 'change'}]
        },
        path: []
      }
    },
    computed: {
      validSwitch: {
        // getter
        get: function () {
          return this.temp.validFlag === '1'
        },
        // setter
        set: function (newValue) {
          if (newValue) {
            this.temp.validFlag = '1'
          } else {
            this.temp.validFlag = '0'
          }
        }
      }
    },
    created() {
      this.showBonus()
    },
    methods: {
      changeExpireType(id) {
        if (id === 7) {
          this.isShow = true
        } else {
          this.isShow = false
          const expireOption = this.$_.find(this.expireOptions, (o) => {
            return o.id === id
          })
          this.selectExpireDay = expireOption.expireDay
        }
      },
      addBonus() {
        const that = this
        this.bonusTemp.useGoods = JSON.stringify(this.selectUseGoods)
        this.$refs['dataForm3'].validate((valid) => {
          if (valid) {
            debugger
            // 获取表单
            const form = this.$refs['dataForm3'].$el
            const formData = new FormData(form)
            for (const key in this.bonusTemp) {
              formData.append(key, this.bonusTemp[key])
            }
            formData.append('path', this.path[0] ? this.path[0].raw : '')
            const config = {
              headers: {
                'Content-Type': 'multipart/form-data'
              }
            }
            SxBonusRecordApi.addBatchUserBonus(formData).then(() => {
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 1000,
                onClose() {

                }
              })
            })
            // SxBonusRecordApi.addUserBonus(this.bonusTemp).then(() => {
            //   this.dialogBonusFormVisible = false
            //   this.$notify({
            //     title: '成功',
            //     message: '添加成功',
            //     type: 'success',
            //     duration: 1000,
            //     onClose() {
            //       that.fetchData()
            //     }
            //   })
            // })
          }
        })
      },
      /**
       * 获取顶级结点
       * */
      getRootData() {
        sxProductBasicInfoApi.getRootData({r: Math.random()}).then((data) => {
          this.productData = data
        })
      },
      showBonus() {
        this.restBonusTemp()
        this.getRootData()
        this.selectExpireDay = 30
        this.selectExpireType = 3
      },
      restBonusTemp() {
        this.bonusTemp = {
          id: '',
          bonusName: '',
          bonusType: '',
          bonusMoney: 0,
          useGoods: '',
          sendType: 0,
          minGoodsAmount: 0,
          bonusNumber: 0,
          bonusImg: '',
          expireTime: new Date().add('dayofyear', 30, true).getTime(),
          sort: 1,
          userId: ''
        }
      },
      handleFile() {
      },
      path_file(file, fileList) {
        this.path = fileList
      }
    },
    watch: {
      selectExpireDay(val) {
        let now = new Date()
        now = now.add('dayofyear', val, true)
        this.bonusTemp.expireTime = now.getTime()
      }
    }
  }
</script>
